#!/usr/bin/env python3
# -*- coding: utf-8 -*-


'''
Pymysql 工具类
'''

import pymysql;

# 获取链接对象、游标对象
def get_connection_cursor():
    connect = pymysql.connect(host="127.0.0.1", port=3306, database="kg20",
                              user="root", password="123456", charset="utf8mb4");
    # 从链接对象中获取游标对象
    cursor = connect.cursor();
    return connect, cursor;

def execute_edit(cursor, sql):
    return cursor.execute(sql);

def execute_query(cursor, sql):
    cursor.execute(sql);
    return cursor.fetchall();

def commit_(connect):
    connect.commit();

def rollback_(connect):
    connect.rollback();

def close_(connect, cursor):
    if cursor:
        cursor.close();
    if connect:
        connect.close();

def execute_edit_(sql):
    result = None;
    connect, cursor = None, None;
    try:
        connect, cursor = get_connection_cursor();
        result = execute_edit(cursor, sql);
        commit_(connect);
    except BaseException as e:
        print(e);
        rollback_(connect);
    finally:
        close_(connect, cursor);

    return result;

def execute_query_(sql):
    result = None;
    connect, cursor = None, None;
    try:
        connect, cursor = get_connection_cursor();
        result = execute_query(cursor, sql);
    except BaseException as e:
        print(e);
    finally:
        close_(connect, cursor);

    return result;
